import React from 'react';
import {
  Input,
  Divider,
  message,
  Form,
  Icon,
  Upload,
  Modal,
} from 'antd';
import PropTypes from 'prop-types';
import { getOwner } from '@/utils/authority';
import config from '../../../../config/web.config';
import SelectCategory from './SelectCategory';

class NormalForm extends React.Component {
  constructor(props) {
    super(props);
    props.saveInstance && props.saveInstance(this);
    this.state = {
      previewVisible: false,
      selectCategoryVisible: false,
    }
  }

  static propTypes  = {
    data: PropTypes.object,
    saveInstance: PropTypes.func.isRequired,
  }

  handleSubmit = (event) => {
    event && event.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) {
        return false;
      }
      const { upload, categoryName, ...rest } = values;
      let picurl;
      const upload0 = upload[0];
      if (!upload0) {
        
      } else if (upload0.picurl){
        picurl = upload0.picurl;
      } else {
        const resp = upload0.response
        if(resp && resp.url){
          picurl = resp.url
        }
      }
      const { data, onSaveForm } = this.props;
      const newCategory = this.newCategory;
      onSaveForm({
        ...rest,
        picurl: picurl,
        subtype: newCategory ? newCategory._id : data.subtype,
        category: newCategory ? newCategory._id : data.subtype,
        id: data._id,
        owner: getOwner(),
        // goodsencode: data.goodsencode,
        // brand:data.brand,
        // producteraddress:data.producteraddress,
        // isactive:data.isactive,
        // applycartype:data.applycartype,
        // productertype: data.productertype,
      });
    });
  }

  componentDidMount(){
    if (this.props.data._id) {
      this.setFieldsValue();
    }
  }

  componentDidUpdate(prevProps){
    if ( prevProps.data._id != this.props.data._id ) {
      this.setFieldsValue();
    }
  }

  setFieldsValue = () => {
    const { data, toptypeid } = this.props;
    this.props.form.setFieldsValue({
      name: data.name,
      saleprice: data.saleprice,
      costprice: data.costprice,
      barcode: data.barcode,
      unit: data.unit,
      minnum: data.minnum,
      remark: data.remark,
      upload: data.picurl ? [{ uid: '2', name: 'hd_s.png', status: 'done',picurl: data.picurl, url: config.HttpUrl+'/file/pic/' + (data.picurl.indexOf('.png')== -1 ?data.picurl+'.png':data.picurl),}] : [],
      categoryName:  data.category ? data.category.name : ''
    });
  }

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };  

  handleCancel = () => {
    this.setState({ 
      previewVisible: false 
    });
  }

  handleSelectCategory = () => {
    this.setState({
      selectCategoryVisible: true,
    });
  }
  handleCancelSelectCategory = () => {
    this.setState({
      selectCategoryVisible: false,
    });
  }

  handleSelectCategorySuccess = (newCategory) => {
    this.handleCancelSelectCategory();
    this.props.form.setFieldsValue({
      categoryName: newCategory.name
    })
    this.newCategory = newCategory;
  }
  
  normFile = e => {
    // console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  beforeUpload2 = (file, fileList) => {
    const isJPG =
      file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJPG) {
      notification.open({
        message: '上传失败',
        description: '只能上传.jpeg,png,jpg格式的图片',
      });
      message.error('只能上传.jpeg,png,jpg格式的图片');
      setTimeout(() => {
        this.setState({ s_picList: [] });
      }, 500);
    }

    const isLt2M = file.size / 1024 < 500;
    if (!isLt2M) {
      alert('图片需要小于500k!');
      setTimeout(() => {
        this.setState({ s_picList: [] });
      }, 500);
    }
    return isLt2M;
  };  

  render() {
    const { getFieldDecorator } = this.props.form;
    const { previewVisible, previewImage, selectCategoryVisible } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    const buttonItemLayout = {
      wrapperCol: { span: 14, offset: 6 },
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );
    const that = this;
    const files = this.props.form.getFieldValue('upload') || [];
    // console.log(files, '-----------')
    return (
      <div>
        <Form layout="horizontal">
          <Form.Item label='商品名称' {...formItemLayout}>
            {
              getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入商品名称' }],
              })(
                <Input placeholder="请输入商品名称" />
              )
            }            
          </Form.Item>
          <Form.Item label='分类' {...formItemLayout}>
            {
              getFieldDecorator('categoryName', {
                rules: [{ required: true, message: '请输入商品名称' }],
              })(
                <Input placeholder="请输入商品名称" addonAfter={
                  <div style={{cursor: 'pointer'}} onClick={this.handleSelectCategory}>选择分类<Icon type="right" /></div>
                } />
              )
            }
          </Form.Item>
          <Form.Item label='默认售价' {...formItemLayout}>
            {
              getFieldDecorator('saleprice', {
                rules: [
                  { required: true, message: '请输入默认售价' },
                  { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入数字最多两位小数' }
                ],
              })(
                <Input placeholder="请输入默认售价" />
              )
            }
          </Form.Item>
          <Form.Item label='成本价' {...formItemLayout}>
            {
              getFieldDecorator('costprice', {
                rules: [
                  { required: true, message: '请输入成本价' },
                  { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入数字最多两位小数' }
                ],
              })(
                <Input placeholder="请输入成本价" />
              )
            }
          </Form.Item>
          <Form.Item label='条形码' {...formItemLayout}>
            {
              getFieldDecorator('barcode', {
                rules: [],
              })(
                <Input placeholder="请输入商品条形码" />
              )
            }
          </Form.Item>
          <Form.Item label='单位' {...formItemLayout}>
            {
              getFieldDecorator('unit', {
                rules: [],
              })(
                <Input placeholder="请输入单位" />
              )
            }
          </Form.Item>
          <Form.Item label='库存预警值' {...formItemLayout}>
            {
              getFieldDecorator('minnum', {
                rules: [{ pattern: /^\d+$/, message: '请输入整数' }],
              })(
                <Input placeholder="请输入库存预警值" />
              )
            }
          </Form.Item>
          <Form.Item label='商品备注' {...formItemLayout}>
            {
              getFieldDecorator('remark', {
                rules: [],
              })(
                <Input placeholder="请输入商品备注" />
              )
            }
          </Form.Item>
          <Form.Item label='图片' {...formItemLayout}>
            {
              getFieldDecorator('upload', {
                rules: [],
                valuePropName: 'fileList',
                getValueFromEvent: this.normFile,
              })(
                <Upload
                  data={{
                    fileName: Date.now(),
                    tel: getOwner(),
                  }}
                  headers={{ tel: getOwner(), type: 1 }}
                  action={'/web/file/picUpload?' + 'tel=' + getOwner()}
                  listType="picture-card"
                  // fileList={that.state.s_picList}
                  beforeUpload={this.beforeUpload2}
                  onPreview={this.handlePreview}
                  onChange={this.handleChange2}
                >
                  { files.length == 0 ?  uploadButton : null}
                </Upload>
              )
            }
          </Form.Item>          
        </Form>
        <Modal
          visible={previewVisible}
          width={600}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
        <Modal
          title="选择分类"
          visible={selectCategoryVisible}
          width={600}
          footer={null}
          onCancel={this.handleCancelSelectCategory}
        >
          <SelectCategory onSelect={this.handleSelectCategorySuccess} />
        </Modal>
      </div>
    );
  }
}


export default Form.create()(NormalForm)